<?php

$self   = $_SERVER['PHP_SELF'];

require_once("../db_login_test.php");
require_once("DB.php");
	
$cnx = connect_to_db();

if (!$cnx) {
	header('Status: 500 No Database Connection');
	die("Couldn't connect to the database!");
}

if (strcmp($HTTP_POST_VARS['auth'], "a457c19eef") != 0) {
		header('Status: 400 Bad Authentication');
		die("Bad Authentication!");
} 


$user_id = $HTTP_POST_VARS['user_id'];
$glucose = 0;
$sample_id = 0;

// Get the glucose reading
if ( isset($HTTP_POST_VARS['glucose']) ) {
	$glucose = $HTTP_POST_VARS['glucose'];
		
	if (strcmp($glucose,"9999") == 0) {
		$glucose = "NULL";
	}
		
}
else {
	header('Status: 500 Don\'t understand format');
	echo "Don't understand format (no glucose found)";
	exit();
}


// Need to actually process pre-tags here!
if ( isset($HTTP_POST_VARS['tags']) ) {
	$tag_str = $HTTP_POST_VARS['tags'];
	$tags = explode(";", $tag_str);	
}
else {
	header('Status: 500 Don\'t understand format');
	echo "Don't understand format (no pre_tags found)";
	exit();
}


// Need to actually process pre-tags here!
if ( isset($HTTP_POST_VARS['sample_id']) ) {
	$sample_id = $HTTP_POST_VARS['sample_id'];
}
else {
	header('Status: 500 Don\'t understand format');
	echo "Don't understand format (no sample_id found)";
	exit();
}

$res = $cnx->query("UPDATE sample SET followup_glucose=$glucose WHERE sample_id=$sample_id");
	
if (DB::isError($res)) {
		
	header("Status: 500 " . DB::errorMessage($res) . "11111"); 
	end_transaction("sample");
	die("Error while updating sample with followup glucose");
}

update_tags($tags);

function update_tags($tag_list) {
	global $cnx, $user_id, $sample_id;
	
	
	foreach ($tag_list as $tag) {
		$res = $cnx->query("SELECT tag_id FROM tag WHERE text=\"$tag\"");
		
		start_transaction("tag");
		// if this is a new tag
		if ($res->numRows() == 0) {
			$cnx->query("INSERT INTO tag (user_id, text, uses) VALUES ".
						"($user_id, \"$tag\", 1)");
						
			$res = $cnx->query("SELECT MAX(tag_id) FROM tag");
	
			$q_data = $res->fetchRow();
			$tag_id = $q_data[0];	
				
				
		} else {
			$q = $res->fetchRow();
			$tag_id = $q[0];
			$cnx->query("UPDATE tag SET uses=uses+1 WHERE tag_id=$tag_id");	
		}
		end_transaction("tag");
		
		$cnx->query("INSERT INTO sample_tag (sample_id, tag_id) " . 
						"VALUES ($this_sample_id, $tag_id)");
	}
}

function start_transaction($table_name) {
	//echo "STARTING TRANSACTION";
	global $cnx;
	$cnx->autoCommit(false);
	$cnx->query("LOCK TABLES ".$table_name." WRITE");
}

function end_transaction($table_name) {
	//echo "ENDING TRANSACTION";
	global $cnx;
	$cnx->commit();
	$cnx->autoCommit(true);
	$cnx->query("UNLOCK TABLES");
}

?>